package org.tinygame.herostory.codec;

import com.google.protobuf.GeneratedMessageV3;
import com.google.protobuf.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import org.tinygame.herostory.msg.GameMsgProtocol;

public class GameMsgDecoder extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(!(msg instanceof BinaryWebSocketFrame)){
            return;
        }
        //websocket 二进制消息会通过 HttpServerCodec 解码成 BinaryWebSocketFrame 类对象
        BinaryWebSocketFrame frame = (BinaryWebSocketFrame) msg;
        ByteBuf byteBuf = frame.content();

        System.out.println(byteBuf);

        int i = byteBuf.readShort();//读取消息长度 - 读取前2个字节
        int msgCode = byteBuf.readShort();//读取消息编号 - 读取后2个字节

        Message.Builder msgBuilder = GameMsgCoder.getBuilderByMsgCode(msgCode);

        if(null == msgBuilder){
            System.out.println("没有拿到Builer");
            return;
        }

        //拿到真实字节数组 - 拿到消息体
        byte [] msgBody = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(msgBody);

        msgBuilder.clear();
        msgBuilder.mergeFrom(msgBody);

        //构建消息
        Message newMsg = msgBuilder.build();

        if(null != newMsg){
            ctx.fireChannelRead(newMsg);
        }

    }
}
